<template>
  <el-card>
    <div slot="header">
      <span>添加账号</span>
    </div>
    <el-form
      status-icon
      :rules="rules"
      size="small"
      label-width="80px"
      class="form"
      :model="formData"
      ref="formRef"
    >
      <el-form-item label="账号" prop="account">
        <el-input v-model="formData.account"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="formData.password"></el-input>
      </el-form-item>
      <el-form-item label="用户组" prop="userGroup">
        <el-select placeholder="请选择用户组" v-model="formData.userGroup">
          <el-option value="超级管理员" label="超级管理员"></el-option>
          <el-option value="普通用户" label="普通用户"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="submit" type="primary">添加</el-button>
        <el-button @click="reset" type="default">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
//解构ajax函数
import {addUserReq, checkUserRepeatReq} from '@/api/user'

//验证账号函数
const checkAccount = async (rule, value, callback) => {
  //非空验证
  if (!value) {
    callback(new Error('账号不能为空'))
    //正则验证
  } else if (!/^[\u4E00-\u9FA5a-zA-Z0-9]{3,16}$/.test(value)) {
    callback(new Error('数字,英文,中文3-16位'))
  } else {
    let res = await checkUserRepeatReq({
      account: value,
    })
    //结构数据
    let {code, msg} = res.data
    //判断
    if (code === 200) {
      // 验证代码重复
      callback()
    } else {
      callback(new Error(msg))
    }
  }
}
//密码
const checkPassword = (rule, value, callback) => {
  //非空验证
  if (!value) {
    callback(new Error('密码不能为空'))
    //正则验证
  } else if (!/^[a-zA-Z0-9_-]{3,16}$/.test(value)) {
    callback(new Error('数字,英文3-16位'))
  } else {
    callback()
  }
}
export default {
  data() {
    return {
      formData: {
        account: '',
        password: '',
        userGroup: '',
      },
      //验证规则
      rules: {
        account: [{validator: checkAccount, trigger: 'blur'}],
        password: [{validator: checkPassword, trigger: 'blur'}],
        userGroup: [{required: true, message: '请选择用户组', trigger: 'blur'}],
      },
    }
  },
  methods: {
    //提交表单
    submit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          //发送请求
          let res = await addUserReq(this.formData)
          //解构数据
          let {code, msg} = res.data
          //判断
          if (code === 0) {
            //跳转
            this.$router.push('/account')
          }
        }
      })
    },
    //重置表单
    reset() {
      this.$refs.formRef.resetFields()
    },
  },
}
</script>

<style lang="scss" scoped>
.form {
  width: 295px;
}
</style>
